import sys
from flask import Flask, render_template, request, jsonify
from sympy import sympify, latex, pi, N

app = Flask(__name__)

server_port = None
running = False


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/calculate', methods=['POST'])
def calculate():
    expression = request.form['expression']
    try:
        result = sympify(expression, locals={'pi': pi})
        result_latex = latex(result)
        return jsonify({'result': str(result), 'latex': result_latex})
    except Exception as e:
        return jsonify({'error': str(e)})


@app.route('/approximate', methods=['POST'])
def approximate():
    expression = request.form['expression']
    try:
        result = sympify(expression, locals={'pi': pi})
        result_approx = N(result)
        result_latex = latex(result_approx)
        return jsonify({'result': str(result_approx), 'latex': result_latex})
    except Exception as e:
        return jsonify({'error': str(e)})


if __name__ == '__main__':
    app.run()
